package com.imooc.sell.service.impl;

import com.imooc.sell.converter.OrderMaster2OrderDTOConverter;
import com.imooc.sell.dataobject.OrderDetail;
import com.imooc.sell.dataobject.OrderMaster;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.dto.CartDTO;
import com.imooc.sell.dto.OrderDTO;
import com.imooc.sell.enums.OrderStatusEnum;
import com.imooc.sell.enums.PayStatusEnum;
import com.imooc.sell.enums.ResultEnum;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.repository.OrderDetailRepository;
import com.imooc.sell.repository.OrderMasterRepository;
import com.imooc.sell.service.OrderService;
import com.imooc.sell.service.ProductInfoService;
import com.imooc.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

  @Autowired
  private ProductInfoService productInfoService;

  @Autowired
  private OrderDetailRepository orderDetailRepository;

  @Autowired
  protected OrderMasterRepository orderMasterRepository;

  @Override
  @Transactional
  public OrderDTO create(OrderDTO orderDTO) {
    BigDecimal orderAmount = new BigDecimal("0");
    //生成订单id
    String orderId = KeyUtil.genUniqueKey();
    orderDTO.setOrderId(orderId);
//    List<CartDTO> cartDTOList = new ArrayList<>();


    //1.查询商品(数量，价格)
    //for循环语法   (循环变量类型  循环变量名称 : 要被遍历的对象) 循环体
    for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
      ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
      //如果找不到商品信息
      if (productInfo == null) {
        throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
      }
      //2.计算总价
      orderAmount = productInfo.getProductPrice()
          .multiply(new BigDecimal(orderDetail.getProductQuantity()))
          .add(orderAmount);
      BeanUtils.copyProperties(productInfo, orderDetail);
      orderDetail.setOrderId(orderId);
      //随机生成一个订单详情id
      orderDetail.setDetailId(KeyUtil.genUniqueKey());
      //订单详情入库
      orderDetailRepository.save(orderDetail);

      //构造购物车对象，传给扣库存的方法
//      CartDTO cartDTO = new CartDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
//      cartDTOList.add(cartDTO);
    }
    //3.写入订单数据库，订单主表和订单详情表
    OrderMaster orderMaster = new OrderMaster();
    BeanUtils.copyProperties(orderDTO, orderMaster);
    orderMaster.setOrderId(orderId);
    orderMaster.setOrderAmount(orderAmount);
    orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
    orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
    orderMasterRepository.save(orderMaster);
    //4.扣库存
    //lambda 表达式方式实现购物车对象list的构建
    List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
        new CartDTO(e.getProductId(), e.getProductQuantity())
    ).collect(Collectors.toList());
    productInfoService.decreaseStock(cartDTOList);
    return orderDTO;
  }

  @Override
  public OrderDTO findOne(String orderId) {
    //查找订单信息
    OrderMaster orderMaster = orderMasterRepository.findById(orderId).orElse(null);
    if (orderMaster == null) {
      throw new SellException(ResultEnum.ORDER_NOT_EXIST);
    }
    //查找订单详情信息
    List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
    if (CollectionUtils.isEmpty(orderDetailList)) {
      throw new SellException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
    }
    OrderDTO orderDTO = new OrderDTO();
    //将orderMaster转成OrderDTC对象
    BeanUtils.copyProperties(orderMaster, orderDTO);
    orderDTO.setOrderDetailList(orderDetailList);
    return orderDTO;
  }

  @Override
  public Page<OrderMaster> findAll(Pageable pageable) {
    return orderMasterRepository.findAll(pageable);
  }

  @Override
  public Page<OrderDTO> findList(String buyerOpenId, Pageable pageable) {
    Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenId, pageable);
    List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());
    return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
  }

  @Override
  public OrderDTO cancel(OrderDTO orderDTO) {
    OrderMaster orderMaster = new OrderMaster();
    //只有新订单才可以被取消
    if (!orderDTO.getOrderStatus().equals((OrderStatusEnum.NEW.getCode()))) {
      log.error("【取消订单】失败，订单状态不正确 orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
      throw new SellException(ResultEnum.ORDER_STATUS_DONE);
    }
    //修改订单状态
    orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
    BeanUtils.copyProperties(orderDTO, orderMaster);

    OrderMaster updateResult = orderMasterRepository.save(orderMaster);
    if (updateResult == null) {
      log.error("【取消订单】取消订单不成功orderMaster={}", orderMaster);
      throw new SellException(ResultEnum.ORDER_CANCEL_ERROR);
    }
    //返还库存，判断订单里面是否有商品，
    if (orderDTO.getOrderDetailList().isEmpty()) {
      throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
    }
    //需要把订单详情转换成购物车对象
    List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(
        e -> new CartDTO(e.getProductId(), e.getProductQuantity())
    ).collect(Collectors.toList());
    productInfoService.increaseStock(cartDTOList);

    //如果已支付，需要退款
    if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
      //TODO
    }
    return orderDTO;
  }

  @Override
  public OrderDTO finish(OrderDTO orderDTO) {
    OrderMaster orderMaster = new OrderMaster();
    //判断订单状态
    if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
      log.error("【完成订单】，订单已取消或订单已完成orderDTO={}", orderDTO);
      throw new SellException(ResultEnum.ORDER_STATUS_DONE);
    }
    orderDTO.setOrderStatus(OrderStatusEnum.DONE.getCode());
    BeanUtils.copyProperties(orderDTO, orderMaster);
    //修改订单状态
    OrderMaster updateResult = orderMasterRepository.save(orderMaster);
    //判断更新是否成功
    if (updateResult == null) {
      log.error("【完成订单】订单状态更新失败orderDTO={}", orderDTO);
      throw new SellException(ResultEnum.ORDER_STATUS_UPDATE_ERROR);
    }
    return orderDTO;
  }

  @Override
  public OrderDTO pay(OrderDTO orderDTO) {
    OrderMaster orderMaster = new OrderMaster();
    //判断订单状态
    if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
      log.error("【支付订单】订单已支付或订单已完成orderDTO={}", orderDTO);
      throw new SellException(ResultEnum.ORDER_STATUS_DONE);
    }
    //判断订单支付状态
    if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
      log.error("【支付订单】订单已支付或订单已完成orderDTO={}", orderDTO);
      throw new SellException(ResultEnum.ORDER_PAY_ERROR);
    }
    orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
    BeanUtils.copyProperties(orderDTO, orderMaster);
    //修改订单支付状态
    OrderMaster updateResult = orderMasterRepository.save(orderMaster);
    if (updateResult == null) {
      log.error("【支付订单】订单状态更新失败orderDTO={}", orderDTO);
      throw new SellException(ResultEnum.ORDER_STATUS_UPDATE_ERROR);
    }
    return orderDTO;
  }
}
